<template>
  <div class="container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-wrapper">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="关键词">
            <el-input v-model="searchForm.keyword" placeholder="请输入关键词" />
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 聊天记录列表 -->
    <div class="chat-list">
      <el-table :data="chatList" style="width: 100%">
        <el-table-column
          prop="userName"
          label="用户姓名"
          align="center"
          header-align="center"
        />
        <el-table-column
          prop="chatInfo"
          label="首条问题"
          show-overflow-tooltip
          :min-width="200"
          align="center"
          header-align="center"
        >
          <template #default="scope">
            <div class="ellipsis">{{ scope.row.chatInfo }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          align="center"
          header-align="center"
        />
        <el-table-column
          fixed="right"
          label="操作"
          width="200"
          align="center"
          header-align="center"
        >
          <template #default="scope">
            <el-button link type="primary" @click="showDetail(scope.row)">
              查看详情
            </el-button>
            <el-button link type="primary" @click="downloadPDF(scope.row)">
              下载PDF
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="聊天详情"
      width="60%"
      :modal="true"
      :center="true"
      class="chat-detail-dialog"
    >
      <div class="chat-detail">
        <div v-for="(item, index) in chatDetail" :key="index" class="message-item">
          <div class="user-message" v-if="item.chatUserType === 'USER'">
            <div class="avatar">👤</div>
            <div class="message-content">{{ item.chatInfo }}</div>
          </div>
          <div class="ai-message" v-else>
            <div class="avatar">🤖</div>
            <div class="message-content">{{ item.chatInfo }}</div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import myAxios from "../../../plugins/myAxios.js";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";

const route = useRoute();
const searchForm = ref({
  keyword: '',
  dateRange: []
});
const chatList = ref([]);
const dialogVisible = ref(false);
const chatDetail = ref([]);

onMounted(() => {
  getChatList();
});

// 获取聊天记录列表
const getChatList = async () => {
  try {
    const res = await myAxios.get('/chatHistory/list', {
      params: {
        keyword: searchForm.value.keyword,
        startDate: searchForm.value.dateRange[0],
        endDate: searchForm.value.dateRange[1]
      }
    })
    chatList.value = res.data;
  } catch (error) {
    ElMessage.error('获取聊天记录失败');
  }
};

// 搜索处理
const handleSearch = () => {
  getChatList();
};

// 显示详情
const showDetail = async (row) => {
  try {
    const res = await myAxios.post(`/chatHistory/detail`,{
      id:row.id,
      conversationId:row.conversationId
    });
    chatDetail.value = res.data;
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取聊天详情失败');
  }
};


// 添加下载 PDF 方法
const downloadPDF = async (row) => {
  try {
    // 获取PDF文件流，设置 responseType 为 'blob'
    const response = await myAxios.get(`/chatHistory/generatePdf?conversationId=${row.conversationId}`, {
      responseType: 'blob'
    });

    // 创建 Blob 对象
    const blob = new Blob([response], { type: 'application/pdf' });
    const url = window.URL.createObjectURL(blob);

    // 创建临时下载链接并触发下载
    const link = document.createElement('a');
    link.href = url;
    link.download = `聊天记录_${row.conversationId}.pdf`;
    document.body.appendChild(link);
    link.click();

    // 清理临时元素和URL
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

  } catch (error) {
    console.error('PDF下载失败:', error);
    ElMessage.error('PDF下载失败');
  }
};


</script>

<style scoped lang="less">
@import "src/assets/css/common.less";

.container {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.search-container {
  width: 100%;
  margin-bottom: 20px;
  display: flex;
  justify-content: center;

  .search-wrapper {
    width: 1000px;  // 可以调整这个固定宽度值
    min-width: 600px;  // 设置最小宽度
  }
}

.chat-list {
  width: 100%;
}

.chat-detail {
    position: relative;
    min-height: 400px;
    padding: 20px;

    .chat-background {
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      z-index: 1;
      pointer-events: none;

      .user-bg, .ai-bg {
        position: absolute;
        height: 200px;
        opacity: 0.1;
      }

      .user-bg {
        left: 20px;
        top: 50%;
        transform: translateY(-50%);
      }

      .ai-bg {
        right: 20px;
        top: 50%;
        transform: translateY(-50%);
      }
    }

    .messages-container {
      position: relative;
      z-index: 2;
    }

    .message-item {
      margin-bottom: 20px;
    }

    .user-message, .ai-message {
      display: flex;
      align-items: flex-start;
      gap: 12px;
      max-width: 80%;
    }

    .user-message {
      margin-left: auto;
      flex-direction: row-reverse;

      .message-content {
        background: #e6f7ff;
        border-radius: 12px 2px 12px 12px;
      }
    }

    .ai-message {
      margin-right: auto;

      .message-content {
        background: #f5f5f5;
        border-radius: 2px 12px 12px 12px;
      }
    }

    .avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .message-content {
      padding: 12px 16px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      line-height: 1.5;
      word-break: break-word;
    }
  }

  .chat-detail-dialog {
    :deep(.el-dialog) {
      margin: 0 !important;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      max-height: 80vh;
      display: flex;
      flex-direction: column;
    }

    :deep(.el-dialog__body) {
      flex: 1;
      overflow: hidden;
    }
  }

  .chat-detail {
    max-height: 60vh;
    overflow-y: auto;
    padding: 20px;

    // 自定义滚动条样式（可选）
    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #dcdfe6;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-track {
      background-color: #f5f7fa;
    }
  }
</style>
